package com.example.cm_network.interceptor

import android.util.Log
import okhttp3.Interceptor
import okhttp3.Response
import okhttp3.ResponseBody
import okio.Buffer
import org.json.JSONArray
import org.json.JSONObject
import java.nio.charset.StandardCharsets
import java.util.concurrent.TimeUnit

/**
 * 简单的网络请求和响应日志拦截器
 * 功能：
 * 1. 记录请求URL、方法、头信息、参数
 * 2. 记录响应状态码、头信息、响应体
 * 3. 计算请求耗时
 * 4. 支持格式化JSON显示
 */
class SimpleLogInterceptor(
    private val tag: String = "NetworkLog"
) : Interceptor {

    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        val startTime = System.nanoTime()
        val requestMethod = request.method
        val requestUrl = request.url.toString()
        Log.d(tag, "Request: $requestMethod $requestUrl")

        val requestHeaders = request.headers
        if (requestHeaders.size > 0) {
            Log.d(tag, "Headers: ${requestHeaders}")
        }

        val requestBody = request.body
        if (requestBody != null) {
            val buffer = Buffer()
            requestBody.writeTo(buffer)
            val bodyStr = buffer.readString(StandardCharsets.UTF_8)
            Log.d(tag, "RequestBody: $bodyStr")
        }

        val response: Response
        try {
            response = chain.proceed(request)
        } catch (e: Exception) {
            Log.e(tag, "Request failed: ${e.message}")
            throw e
        }

        val endTime = System.nanoTime()
        val duration = TimeUnit.NANOSECONDS.toMillis(endTime - startTime)

        val responseCode = response.code
        val responseMessage = response.message

        Log.d(tag, "Response: $responseCode $responseMessage (${duration}ms)")

        val responseHeaders = response.headers
        if (responseHeaders.size > 0) {
            Log.d(tag, "ResponseHeaders: ${responseHeaders}")
        }

        val responseBody = response.body
        if (responseBody != null) {
            val contentType = responseBody.contentType()
            val responseBodyString = responseBody.string()

            val formattedBody = try {
                if (responseBodyString.startsWith("{")) {
                    JSONObject(responseBodyString).toString(2)
                } else if (responseBodyString.startsWith("[")) {
                    JSONArray(responseBodyString).toString(2)
                } else {
                    responseBodyString
                }
            } catch (e: Exception) {
                responseBodyString
            }

            Log.d(tag, "ResponseBody: $formattedBody")

            val newResponseBody = ResponseBody.create(
                contentType,
                responseBodyString
            )

            return response.newBuilder()
                .body(newResponseBody)
                .build()
        }

        return response
    }
}